package com.mojo.concurrent.waitandnotify;

/**
 * 线程等待与唤醒
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class WaitAndNotify {

    public static void main(String[] args) {
        Object obj = new Object();
        //线程等待，放弃CPU的使用权
        //其他线程执行，调用notify方法，唤醒其他线程
        //使用锁对象调用wait和notify方法
        new Thread(() -> {

            while (true) {
                synchronized (obj) {
                    System.out.println("11111到饭店，等待上菜");
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("11111上菜完毕，吃饭。。。");
                    System.out.println("==========================");
                }
            }
        }).start();
        new Thread(() -> {

            while (true) {
                synchronized (obj) {
                    System.out.println("22222到饭店，等待上菜");
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("22222上菜完毕，吃饭。。。");
                    System.out.println("==========================");
                }
            }
        }).start();
        new Thread(() -> {
            while (true) {
                try {
                    //睡眠，让等待线程先获取锁
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj) {
                    System.out.println("后厨做饭");
                    obj.notify();
                    System.out.println("做饭完毕，上菜。。。");
                }
            }
        }).start();
    }
}
